package com.sxsihe.heartmate;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.*;

import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;
import com.sxsihe.heartmate.util.ECGParse;
import com.sxsihe.heartmate.util.FileStates;
import com.sxsihe.heartmate.util.SharePreferenceUtil;
import com.sxsihe.heartmate.view.CurveView;
import com.sxsihe.heartmate.view.TimePopupWindow;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SerialDataActivity extends Activity implements View.OnClickListener {
    private final String TAG = SerialDataActivity.class.getSimpleName();
    private static UsbSerialPort sPort = null;
    private ECGParse ep = new ECGParse();
    private Button mBtnSave, save_btn, draw_btn, signal_btn, linked_btn;
    long time_start, time_end;
    boolean isDraw = false;
    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
    private SerialInputOutputManager mSerialIoManager;
    Drawable signalDrawable1, signalDrawable2, linkDrawable1, linkDrawable2;
    LinearLayout root_layout;
    CheckBox save;
    int rateMin,rateMax;
    private Vibrator vibrator;
    boolean beginVibrator,is_alarm = false;
    int duration;

    private final SerialInputOutputManager.Listener mListener =
            new SerialInputOutputManager.Listener() {

                @Override
                public void onRunError(Exception e) {
                    Log.d(TAG, "Runner stopped.");
                }

                @Override
                public void onNewData(final byte[] data) {
                    SerialDataActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            SerialDataActivity.this.updateReceivedData(data);
                        }
                    });
                }
            };

    CurveView mCurveView;
    TextView heartratevalue, result_btn;
    SharePreferenceUtil spu;
    Button diagnose;
    boolean mIsSaving = false;
    FileOutputStream mFileWriter;
    String isRecord = "0";
    int averHeartRate, heartCount, _r2r, _mood, _stress, _heart_age, mPoorSignal;
    ImageView back_icon;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.serial_console);
        setContentView(R.layout.realtime2);
        root_layout = (LinearLayout)findViewById(R.id.root_layout);
//        duration = this.getIntent().getIntExtra("duration",0);
        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        if (spu == null) {
            spu = SharePreferenceUtil.getInstance(this);
        }
        rateMin = Integer.parseInt(spu.get("rateMin", "60"));
        rateMax = Integer.parseInt(spu.get("rateMax", "100"));
        is_alarm = Boolean.valueOf(spu.get("is_alarm", "true"));

        mCurveView = (CurveView) this.findViewById(R.id.curveView);
        ep.setView(mCurveView);
        ep.setActivity(this);

//        heartratetext.setTextColor(spu.getColor("text_color", getResources().getColor(R.color.ecgview_text_color)));
        heartratevalue = (TextView) this.findViewById(R.id.heartratevalue);
        save = (CheckBox) findViewById(R.id.save);
        save.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                try {
                    if (isChecked) {
                        showTimeWindow();
//                        String file = new Date().getTime() + ".data";
//                        mIsSaving = true;
//                        FileStates.changed = true;
//                        mFileWriter = openFileOutput(file, Context.MODE_PRIVATE);
                    } else {
                        try {
                            handler.removeCallbacks(autoRun);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        time_end = System.currentTimeMillis();
                        mIsSaving = false;
                        int status = 0;
                        if (averHeartRate >= 60 && averHeartRate <= 90) {
                            status = 1;
                        }
                        String tmp = "averHeartRate:" + averHeartRate;
                        tmp += "|heart_age:" + _heart_age +
                                "|heart_count:" + heartCount +
                                "|r2r:" + _r2r +
                                "|mood:" + _mood +
                                "|stress:" + _stress +
                                "|signal:" + mPoorSignal +
                                "|status:" + status +
                                "|type:serial"+
                                "|duration:" + (int) (time_end - time_start) / 1000;
                        mFileWriter.write(tmp.getBytes());
                        mFileWriter.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        draw_btn = (Button) findViewById(R.id.draw_btn);
        draw_btn.setOnClickListener(this);

        back_icon = (ImageView) findViewById(R.id.back_icon);
        back_icon.setOnClickListener(this);

        result_btn = (TextView) findViewById(R.id.result_btn);
        result_btn.setOnClickListener(this);

        signal_btn = (Button) findViewById(R.id.signal_btn);
        linked_btn = (Button) findViewById(R.id.linked_btn);
        signalDrawable1 = getResources().getDrawable(R.drawable.signal1);
        signalDrawable1.setBounds(0, 0, signalDrawable1.getMinimumWidth(), signalDrawable1.getMinimumHeight());
        signalDrawable2 = getResources().getDrawable(R.drawable.signal2);
        signalDrawable2.setBounds(0, 0, signalDrawable2.getMinimumWidth(), signalDrawable2.getMinimumHeight());

        linkDrawable1 = getResources().getDrawable(R.drawable.link1);
        linkDrawable1.setBounds(0, 0, linkDrawable1.getMinimumWidth(), linkDrawable1.getMinimumHeight());
        linkDrawable2 = getResources().getDrawable(R.drawable.link2);
        linkDrawable2.setBounds(0, 0, linkDrawable2.getMinimumWidth(), linkDrawable2.getMinimumHeight());

        if (sPort == null) {
            linked_btn.setText("未连接");
            linked_btn.setCompoundDrawables(null, linkDrawable1, null, null);
            signal_btn.setCompoundDrawables(null, signalDrawable1, null, null);
            signal_btn.setText("信号0%");
        } else {
            linked_btn.setText("已连接");
            linked_btn.setCompoundDrawables(null, linkDrawable2, null, null);
        }



    }

    Handler handler = new Handler();
    Runnable autoRun = new Runnable() {
        @Override
        public void run() {
            save.performClick();
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeCallbacks(autoRun);
    }


    private long startTime = 0;

    public void writeFile(int data) {
        if (mIsSaving) {
            long mills = Calendar.getInstance().getTimeInMillis();
            String line = mills + "|" + (0-data) + "|"+(averHeartRate==0?" ":averHeartRate)+ "\r\n";
            try {
                mFileWriter.write(line.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save:
//                String file = new Date().getTime() + ".data";
//                try {
//                    mIsSaving = !mIsSaving;
//                    if (mIsSaving) {
//                        FileStates.changed = true;
//                        save.setText("停止记录");
//                        isRecord = "1";
//                        mFileWriter = openFileOutput(file, Context.MODE_PRIVATE);
//
//                    } else {
//                        save.setText("开始记录");
//                        try {
//                            mFileWriter.close();
//
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
                break;
            case R.id.draw_btn:
//                if(!isDraw){
//                    showTimeWindow();
//
//                } else {
//                    draw_btn.setText("开始绘制");
//                    time_start = System.currentTimeMillis();
//                    if(mIsSaving)save.setChecked(false);
//                    try{
//                        handler.removeCallbacks(autoRun);
//                    }catch (Exception e){
//
//                    }
//                    isDraw = !isDraw;
//                    ep.setIsDraw(isDraw);
//                }
                if (isDraw) {
                    draw_btn.setText("开始绘制");
                    time_end = System.currentTimeMillis();
                } else {
                    draw_btn.setText("停止绘制");
                    time_start = System.currentTimeMillis();

                }
                isDraw = !isDraw;
                ep.setIsDraw(isDraw);
                break;
            case R.id.back_icon:
                isDraw = false;
                save.setChecked(false);
                SerialDataActivity.this.finish();
                break;
            case R.id.result_btn:
                if (time_start != 0)
                    time_end = System.currentTimeMillis();
                if (save.isChecked()) {
                    save.performClick();
                }
                if (isDraw) {
                    draw_btn.performClick();
                }
                final int _heartrate = averHeartRate >= 160 ? 160 : averHeartRate;
                Intent intent = new Intent(SerialDataActivity.this, DiagnoseActiviy2.class);
                intent.putExtra("heart_age", _heart_age + "");
                intent.putExtra("heart_count", heartCount + "");
                intent.putExtra("r2r", _r2r + "");
                intent.putExtra("mood", _mood + "");
                intent.putExtra("stress", _stress + "");
                intent.putExtra("heartrate", _heartrate + "");
                intent.putExtra("signal", mPoorSignal / 2 + "%");
                intent.putExtra("duration", (int) (time_end - time_start) / 1000 + "");
                intent.putExtra("type", "serial");
                startActivity(intent);
                finish();
                break;
            case R.id.btn_1min:
                duration = 60000;
                try {
                    popWindow.dismiss();
                    time_start = System.currentTimeMillis();

                    String file = new Date().getTime() + ".data";
                    mIsSaving = true;
                    FileStates.changed = true;
                    mFileWriter = openFileOutput(file, Context.MODE_PRIVATE);
                    if (duration != 0) {
                        handler.postDelayed(autoRun, duration);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
//                popWindow.dismiss();
//                save.performClick();
//                if (isDraw) {
//                    draw_btn.setText("开始绘制");
//                    time_end = System.currentTimeMillis();
//                } else {
//                    draw_btn.setText("停止绘制");
//                    time_start = System.currentTimeMillis();
//                }
//                isDraw = !isDraw;
//                ep.setIsDraw(isDraw);
//                if(duration!=0){
//                    handler.postDelayed(autoRun, duration);
//                }
                break;
            case R.id.btn_3min:
                duration = 180000;
                try {
                    popWindow.dismiss();
                    time_start = System.currentTimeMillis();
                    String file = new Date().getTime() + ".data";
                    mIsSaving = true;
                    FileStates.changed = true;
                    mFileWriter = openFileOutput(file, Context.MODE_PRIVATE);
                    if (duration != 0) {
                        handler.postDelayed(autoRun, duration);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_no_limit:
                duration = 0;
                try {
                    popWindow.dismiss();
                    time_start = System.currentTimeMillis();

                    String file = new Date().getTime() + ".data";
                    mIsSaving = true;
                    FileStates.changed = true;
                    mFileWriter = openFileOutput(file, Context.MODE_PRIVATE);
                    if (duration != 0) {
                        handler.postDelayed(autoRun, duration);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                break;

        }
    }

    TimePopupWindow popWindow;
    public void showTimeWindow(){
        if(popWindow!=null&&popWindow.isShowing()){
            return;
        }
        popWindow = new TimePopupWindow(this, this);
        popWindow.showAtLocation(root_layout, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void setHeartRate(int heartRate) {
        averHeartRate = heartRate;
        if(heartRate<rateMin||heartRate>rateMax){
            heartratevalue.setTextColor(Color.RED);
        }else{
            heartratevalue.setTextColor(Color.parseColor("#9A9A9A"));
        }
        heartratevalue.setText(heartRate + "");
    }

    public void toggleDevSignal(int signal) {
        mPoorSignal = signal;
        if (signal != 0) {
            signal_btn.setCompoundDrawables(null, signalDrawable2, null, null);
        } else {
            signal_btn.setCompoundDrawables(null, signalDrawable1, null, null);
            heartratevalue.setText("");


        }
        signal_btn.setText("信号" + signal / 2 + "%");
    }



    @Override
    protected void onPause() {
        super.onPause();
        if(mIsSaving){
            save.performClick();
        }
        if(isDraw){
            draw_btn.performClick();
        }
        stopIoManager();
        if (sPort != null) {
            try {
                sPort.close();
            } catch (IOException e) {
                // Ignore.
            }
            sPort = null;
        }
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        draw_btn.setText("开始绘制");
        Log.d(TAG, "Resumed, port=" + sPort);
        if (sPort == null) {
        } else {
            final UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

            UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
            if (connection == null) {
//                Toast.makeText(this, "aaa", Toast.LENGTH_SHORT);
                return;
            }
//            Toast.makeText(this, "bbb", Toast.LENGTH_SHORT);

            try {
                sPort.open(connection);
                sPort.setParameters(57600, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            } catch (IOException e) {
                Log.e(TAG, "Error setting up device: " + e.getMessage(), e);
                //mTitleTextView.setText("Error opening device: " + e.getMessage());
                try {
                    sPort.close();
                } catch (IOException e2) {
                    // Ignore.
                }
                sPort = null;
                return;
            }
            //mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName());
        }
        onDeviceStateChange();
    }

    private void stopIoManager() {
        if (mSerialIoManager != null) {
//            Log.i(TAG, "Stopping io manager ..");
            mSerialIoManager.stop();
            mSerialIoManager = null;
        }
    }

    private void startIoManager() {
        if (sPort != null) {
            mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
            mExecutor.submit(mSerialIoManager);
        }
    }

    private void onDeviceStateChange() {
        stopIoManager();
        startIoManager();
    }

    private void updateReceivedData(byte[] data) {

//            if (!save.isEnabled() && !mIsSaving) {
//                save.setEnabled(true);
//            }
//        System.out.println(mPoorSignal);
//        if(mPoorSignal==0){
//            data = new byte[]{-86,-86,4,-128,2,0,107,18};
//        }
        ep.push(data);
        ep.parse();


    }

    /**
     * Starts the activity, using the supplied driver instance.
     */
    static void show(Context context, UsbSerialPort port) {
//        sPort = port;
//        final Intent intent = new Intent(context, SerialDataActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
//        context.startActivity(intent);

        sPort = port;
        final Intent intent = new Intent(context, SerialDataActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
        //跳转时带的标识符
        int requestCode = 0;
        ((Activity) context).startActivityForResult(intent, requestCode);
    }
}
